{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "606b083c-aabd-4c62-99e0-03d2bbf73c36",
   "metadata": {
    "vscode": {
     "languageId": "python"
    }
   },
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.metrics import classification_report\n",
    "from joblib import dump\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.metrics import accuracy_score, classification_report\n",
    "\n",
    "class Classification:\n",
    "    def __init__(self):\n",
    "        self.df = pd.read_csv('daily.csv')\n",
    "        print(\"数据列名:\", self.df.columns.tolist())  # 打印列名确认\n",
    "\n",
    "    def get_condition(self):\n",
    "        df = self.df\n",
    "\n",
    "        \n",
    "        \n",
    "        # 使用正确的列名计算比率\n",
    "        df['new_ratio'] = df['max_close'] / df['the_slose']\n",
    "        df['min_ratio'] = df['min_close'] / df['the_slose']\n",
    "\n",
    "        high_return_threshold = df['new_ratio'].quantile(0.4)\n",
    "        high_risk_threshold = df['min_ratio'].quantile(0.4)\n",
    "\n",
    "        conditions = [\n",
    "            (df['new_ratio'] >= high_return_threshold) & (df['min_ratio'] <= high_risk_threshold),\n",
    "            (df['new_ratio'] >= high_return_threshold) & (df['min_ratio'] > high_risk_threshold),\n",
    "            (df['new_ratio'] < high_return_threshold) & (df['min_ratio'] > high_risk_threshold),\n",
    "            (df['new_ratio'] < high_return_threshold) & (df['min_ratio'] < high_risk_threshold),\n",
    "        ]\n",
    "        \n",
    "        labels = ['高收益高风险', '高收益低风险', '低收益低风险', '低收益高风险']\n",
    "        df['category'] = np.select(conditions, labels, default='未知')\n",
    "\n",
    "        features = df[['eps', 'total_revenue_ps', 'undist_profit_ps', 'gross_margin',\n",
    "                      'fcff', 'fcfe', 'bps', 'grossprofit_margin']]\n",
    "\n",
    "        le = LabelEncoder()\n",
    "        df['category_crossed'] = le.fit_transform(df['category'])\n",
    "        \n",
    "        X_train, X_test, y_train, y_test = train_test_split(\n",
    "            features, df['category_crossed'], test_size=0.3, random_state=24)\n",
    "            \n",
    "        return X_train, X_test, y_train, y_test, le\n",
    "\n",
    "    def knn_utils(self, X_train, X_test, y_train, y_test, le):\n",
    "        knn = KNeighborsClassifier(n_neighbors=5)\n",
    "        knn.fit(X_train, y_train)\n",
    "        y_pred = knn.predict(X_test)\n",
    "        \n",
    "        dump(knn, 'knn_classifier.joblib')\n",
    "        dump(le, 'label_encoder.joblib')\n",
    "        \n",
    "        print(classification_report(y_test, y_pred, target_names=le.classes_))\n",
    "\n",
    "    def svc_utils(self, X_train, X_test, y_train, y_test):\n",
    "        svc = SVC()\n",
    "        svc.fit(X_train, y_train)\n",
    "        predictions = svc.predict(X_test)\n",
    "        print(\"Accuracy score: %.4f\" % accuracy_score(predictions, y_test))\n",
    "        print(\"Classification report for classifier:\\n%s\\n\" % classification_report(y_test, predictions))\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    ci = Classification()\n",
    "    X_train, X_test, y_train, y_test, le = ci.get_condition()\n",
    "    ci.knn_utils(X_train, X_test, y_train, y_test, le)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "",
   "name": ""
  },
  "language_info": {
   "name": ""
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
